package com.ubb.damate.controller;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;

import com.ubb.damate.beans.UserSessionBean;
import com.ubb.damate.model.Role;
import com.ubb.damate.model.User;
import com.ubb.damate.model.UserModel;
import com.ubb.damate.service.UserServiceRemote;

@ManagedBean
public class UserController {

	@ManagedProperty(value = "#{user}")
	private UserModel userModel;
	
	@ManagedProperty(value = "#{userSession}")
	private UserSessionBean userSessionBean;

	@EJB(beanName = "UserService")
	private UserServiceRemote userService;	

	public UserModel getUserModel() {
		return userModel;
	}

	public void setUserModel(UserModel userModel) {
		this.userModel = userModel;
	}

	public UserSessionBean getUserSessionBean() {
		return userSessionBean;
	}

	public void setUserSessionBean(UserSessionBean userSessionBean) {
		this.userSessionBean = userSessionBean;
	}

	public String createUser() {
		User newUser = new User();
		newUser.setUsername(userModel.getUsername());
		newUser.setPassword(DigestUtils.md5Hex(userModel.getPassword()));
		newUser.setFirstname(userModel.getFirstname());
		newUser.setLastname(userModel.getLastname());
		newUser.setGender(userModel.getGender());
		newUser.setEmail(userModel.getEmail());
		newUser.setState(0);
		Role admin = new Role();
		admin.setRoleId(1);
		admin.setRoleName("user");
		newUser.setRole(admin);
		userService.createOrUpdate(newUser);
		return "/login.jsf";
	}
	
	public String login() {
		if (userService.login(userModel.getUsername(), DigestUtils.md5Hex(userModel.getPassword()))) {
			User loggedUser = new User();
			loggedUser.setUsername(userModel.getUsername());
			loggedUser = userService.find(loggedUser);
			userSessionBean.setUsername(loggedUser.getUsername());
			userSessionBean.setName(loggedUser.getFirstname() + " " + loggedUser.getLastname());
			userSessionBean.setActive(loggedUser.getState() == 1 ? true : false);
			userSessionBean.setRole(loggedUser.getRole().getRoleName());
			userSessionBean.setAuthorized(true);
			return "pages/mainPage.jsf";
		}
		return null;
	}
	
	public String logout() {
		ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
		request.getSession().invalidate();
		return "/login.jsf";
	}
}
